package com.geqian.web.chat;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
import java.util.List;
import java.util.Map;

/**
 * 响应 Sec-WebSocketResponseFilter-Protocol 请求头参数
 * （因为前端通过 websocket 连接时指定了 Sec-WebSocketResponseFilter-Protocol，所以后端接收到连接后，
 *  必须原封不动的将 Sec-WebSocketResponseFilter-Protocol 头信息返回给前端，否则连接会抛出异常。）
 */
public class WebSocketResponseConfigurator extends Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {

        super.modifyHandshake(config, request, response);

        // 获取客户端请求头部
        Map<String, List<String>> headers = request.getHeaders();

        List<String> protocols = headers.get("Sec-WebSocket-Protocol");

        if (protocols != null) {
            // 设置响应的协议头部
            response.getHeaders().put("Sec-WebSocket-Protocol", protocols);
        }
    }

}